package com.cxb.manager;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import android.content.Context;
import android.util.Log;

public class RootContext {
	private static RootContext instance = null;
	String mShell;
	OutputStream o;
	Process p;

	private RootContext(String paramString) throws Exception {
		this.mShell = paramString;
		init();
	}

	public static RootContext getInstance() {

		RootContext localRootContext = null;
		if (instance != null) {
			localRootContext = instance;
			return localRootContext;
		}

		try {
			instance = new RootContext("su");
			localRootContext = instance;
		} catch (Exception localException2) {
			try {
				instance = new RootContext("/system/xbin/su");
				localRootContext = instance;
			} catch (Exception localException3) {
				try {
					instance = new RootContext("/system/bin/su");
					localRootContext = instance;
				} catch (Exception localException1) {
					localException1.printStackTrace();
				}
			}
		}
		return localRootContext;

	}

	private void init() throws Exception {
		if ((this.p != null) && (this.o != null)) {
			this.o.flush();
			this.o.close();
			this.p.destroy();
		}
		this.p = Runtime.getRuntime().exec(this.mShell);
		this.o = this.p.getOutputStream();
	}

	private void system(String paramString) {
		try {
			this.o.write(("LD_LIBRARY_PATH=/vendor/lib:/system/lib "
					+ paramString + "\n").getBytes("ASCII"));
			return;
		} catch (Exception localException2) {
			try {
				init();
			} catch (Exception localException1) {
				localException1.printStackTrace();
			}
		}
	}

	public static String runCommandForResult(String cmd) {
		String result = "";
		DataOutputStream dos = null;
		DataInputStream dis = null;

		try {
			Process p = Runtime.getRuntime().exec("su");// 经过Root处理的android系统即有su命令
			dos = new DataOutputStream(p.getOutputStream());
			dis = new DataInputStream(p.getInputStream());

			dos.writeBytes(cmd + "\n");
			dos.flush();
			dos.writeBytes("exit\n");
			dos.flush();
			String line = null;
			while ((line = dis.readLine()) != null) {
				Log.d("result", line);
				result += line;
			}
			p.waitFor();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (dos != null) {
				try {
					dos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (dis != null) {
				try {
					dis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}

	public void runCommand(String command) {
//		system(command);
		runCommandForResult(command);
	}
}
